<?php 
/*
 module:		我的活动
 create_time:	2022-03-28 11:45:28
 author:	陕西格创
 contact:		
*/

namespace app\api\controller;

use app\api\service\ZhMyActivityService;
use app\api\model\ZhMyActivity as ZhMyActivityModel;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use app\backend\model\ZhSignUp as ZhSignUpModel;
use app\backend\model\SysSite as SysSiteModel;
use app\api\model\Member as MemberModel;
use app\api\model\ZhActivity as ZhActivityModel;


class ZhMyActivity extends Common {


	/**
	* @api {get} /ZhMyActivity/view 01、查看详情
	* @apiGroup ZhMyActivity
	* @apiVersion 1.0.0
	* @apiDescription  查看详情
	
	* @apiParam (输入参数：) {string}     		article_id 主键ID
	* @apiParam (输入参数：) {string}     		600px 主键ID
	* @apiParam (输入参数：) {string}     		300px 主键ID

	* @apiHeader {String} Authorization 用户授权token
	* @apiHeaderExample {json} Header-示例:
	* "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"

	* @apiParam (失败返回参数：) {object}     	array 返回结果集
	* @apiParam (失败返回参数：) {string}     	array.status 返回错误码 201
	* @apiParam (失败返回参数：) {string}     	array.msg 返回错误消息
	* @apiParam (成功返回参数：) {string}     	array 返回结果集
	* @apiParam (成功返回参数：) {string}     	array.status 返回错误码 200
	* @apiParam (成功返回参数：) {string}     	array.data 返回数据详情
	* @apiSuccessExample {json} 01 成功示例
	* {"status":"200","data":""}
	* @apiErrorExample {json} 02 失败示例
	* {"status":"201","msg":"没有数据"}
	*/
	function view(){
        $wxapp_id       = $this->request->get('wxapp_id');
        $uId            = $this->request->uid;
        $activityId     = $this->request->get('activity_id','','serach_in');
        if(!$wxapp_id){
            return $this->ajaxReturn($this->errorCode,'缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id',$wxapp_id)->find();
        if(!$wxSetting){
            return $this->ajaxReturn($this->errorCode,'平台参数未配置');
        }
        
        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find()->toArray();
        if(!$user){
            return $this->ajaxReturn($this->errorCode,'未知用户');
        }
        $data['activity_id'] = $activityId;
        $data['wxapp_id']    = $wxapp_id;
        $field               = 'title,subtitle,start_time,address,coordinate,activity_num,activity_id,wxapp_id,sign_up_start_time,sign_up_end_time';
        $res = checkData(ZhActivityModel::field($field)->where($data)->find());
        $time = time();
        if($time < $res['sign_up_start_time'] || $time > $res['sign_up_end_time']){
            $res['is_cancel'] = 0;
        }else {
            $res['is_cancel'] = 1;
        }
        $res['start_time'] = date('Y-m-d H:i:s',$res['start_time']);
        $res['sign_up_start_time'] = date('Y-m-d',$res['sign_up_start_time']);
        $res['sign_up_end_time']   = date('Y-m-d',$res['sign_up_end_time']);
        $res['phone']      = $user['phone'];
        $res['real_name']  = $user['real_name'];
        $orderSn =  ZhSignUpModel::where(['activity_id'=> $activityId,'wxapp_id'=> $wxapp_id,'u_id'=> $uId,'status'=> 1])->value('order_sn');
        $res['order_sn'] = $orderSn;
        $signUpNum = ZhSignUpModel::where(['activity_id'=> $activityId,'wxapp_id'=> $wxapp_id,'status'=> 1])->count('sign_up_id');
        $res['sign_up_num'] = $signUpNum;
        $res['coordinate']  = json_decode($res['coordinate']);
        
		return $this->ajaxReturn($this->successCode,'返回成功',$res);
	}

	/**
	* @api {get} /ZhMyActivity/index 02、首页数据列表
	* @apiGroup ZhMyActivity
	* @apiVersion 1.0.0
	* @apiDescription  首页数据列表

	* @apiHeader {String} Authorization 用户授权token
	* @apiHeaderExample {json} Header-示例:
	* "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"

	* @apiParam (输入参数：) {int}     		[limit] 每页数据条数（默认20）
	* @apiParam (输入参数：) {int}     		[page] 当前页码

	* @apiParam (失败返回参数：) {object}     	array 返回结果集
	* @apiParam (失败返回参数：) {string}     	array.status 返回错误码 201
	* @apiParam (失败返回参数：) {string}     	array.msg 返回错误消息
	* @apiParam (成功返回参数：) {string}     	array 返回结果集
	* @apiParam (成功返回参数：) {string}     	array.status 返回错误码 200
	* @apiParam (成功返回参数：) {string}     	array.data 返回数据
	* @apiParam (成功返回参数：) {string}     	array.data.list 返回数据列表
	* @apiParam (成功返回参数：) {string}     	array.data.count 返回数据总数
	* @apiSuccessExample {json} 01 成功示例
	* {"status":"200","data":""}
	* @apiErrorExample {json} 02 失败示例
	* {"status":" 201","msg":"查询失败"}
	*/
	function index(){
        $wxapp_id       = $this->request->get('wxapp_id');
        $uId            = $this->request->uid;
        $type           = $this->request->get('type');
        $title          = $this->request->get('title','','serach_in');
        if(!$wxapp_id){
            return $this->ajaxReturn($this->errorCode,'缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id',$wxapp_id)->find();
        if(!$wxSetting){
            return $this->ajaxReturn($this->errorCode,'平台参数未配置');
        }
        
        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if(!$user){
            return $this->ajaxReturn($this->errorCode,'未知用户');
        }
        $where1 = [];
        $where1['u_id'] = $uId;
        $where1['wxapp_id'] = $wxapp_id;
        $where1['status'] = 1;
        if ($type && $type == 2){
            $where1['activity_status'] = 2;
        }elseif($type && $type != 2 && $type != 0) {
            $where1['activity_status'] = 1;
        }
        $activityIdData = ZhSignUpModel::where($where1)->column('activity_id');
		$limit   = $this->request->get('limit', 20, 'intval');
		$page    = $this->request->get('page', 1, 'intval');

		$newTime = time();
		$where   = [];
		$where[] = ['wxapp_id','=',$wxapp_id];
		if($type && $type == 1){
		    $where[] = ['start_time','>',$newTime];
        }
        if($type && $type == 3){
            $where[] = ['start_time','<=',$newTime];
        }
		$field   = '*';
		$orderby = 'activity_id desc';
        
        $res = ZhMyActivityModel::where($where)
                                ->whereIn('activity_id',$activityIdData)
                                ->where('title','like','%' . $title . '%')
                                ->field($field)
                                ->order($orderby)
                                ->paginate(['list_rows'=>$limit,'page'=>$page])
                                ->toArray();
        foreach ($res['data'] as &$v){
            $isCanjia = ZhSignUpModel::where([
                                        'u_id'=> $uId,
                                        'wxapp_id'=> $wxapp_id,
                                        'activity_id'=> $v['activity_id']
                                    ])->value('activity_status');
            if($isCanjia == 2){
                $v['type'] = 2;
            }else {
                $v['type'] = $v['start_time'] > $newTime ? 1 : 0;
            }
            $v['start_time']         = date('Y-m-d H:i:s',$v['start_time']);
            $v['sign_up_start_time'] = date('Y-m-d',$v['sign_up_start_time']);
            $v['sign_up_end_time']   = date('Y-m-d H:i:s',$v['sign_up_end_time']);
            $v['createtime']         = date('Y-m-d H:i:s',$v['createtime']);
            $v['images']             = json_decode(html_out($v['images']),true);
            $v['coordinate']         = json_decode(html_out($v['coordinate']),true);
//            $v['fengmiantu']         = $this->request->domain() . $v['images'][0]['url'];
            $v['fengmiantu']         = $v['images'][0]['url'];
        }
        unset($v);
		return $this->ajaxReturn($this->successCode,'返回成功',htmlOutList($res));
	}
    
    /**获取核销活动订单详情**/
    function heXiaoShuJu(){
        $orderSn    = $this->request->get('order_sn');
        $signUpData = ZhSignUpModel::where(['order_sn'=> $orderSn,'status'=> 1])->find();
        $field      = 'title,subtitle,start_time,address,coordinate,activity_num,activity_id,wxapp_id';
        $data       = [
            'activity_id'=> $signUpData['activity_id'],
            'wxapp_id'   => $signUpData['wxapp_id']
        ];
        $res  = checkData(ZhActivityModel::field($field)->where($data)->find());
        $user = MemberModel::where([
                                'uid'     => $signUpData['u_id'],
                                'wxapp_id'=> $signUpData['wxapp_id']
                            ])
                           ->find()->toArray();
        $res['start_time'] = date('Y-m-d H:i:s',$res['start_time']);
        $res['phone']      = $user['phone'];
        $res['real_name']  = $user['real_name'];
        
        $res['order_sn']   = $orderSn;
        $signUpNum         = ZhSignUpModel::where([
                                                'activity_id'=> $signUpData['activity_id'],
                                                'wxapp_id'   => $signUpData['wxapp_id'],
                                                'status'     => 1
                                            ])->count('sign_up_id');
        $res['sign_up_num'] = $signUpNum;
        return $this->ajaxReturn($this->successCode,'返回成功',$res);
    }
    
    /**核销活动订单**/
    function heXiao(){
        $orderSn    = $this->request->get('order_sn');
        $signUpData = ZhSignUpModel::where(['order_sn'=> $orderSn,'status'=> 1])->find();
        $field      = 'start_time,address,activity_id,wxapp_id';
        $data       = [
            'activity_id'=> $signUpData['activity_id'],
            'wxapp_id'   => $signUpData['wxapp_id']
        ];
        $ActivityData = checkData(ZhActivityModel::field($field)->where($data)->find());
        $time         = time();
      
        if($time < $ActivityData['start_time']){
            return $this->ajaxReturn($this->errorCode,'活动未开始，核销失败');
        }
        $res = ZhSignUpModel::where([
                        'activity_id'=> $signUpData['activity_id'],
                        'wxapp_id'   => $signUpData['wxapp_id'],
                        'status'     => 1
                        ])->update(['activity_status'=> 2]);
        if($res){
            return $this->ajaxReturn($this->successCode,'核销成功',$res);
        }else{
            return $this->ajaxReturn($this->errorCode,'该订单已核销，无需重复核销');
        }
        
    }
    
	

}

